import React, {Component} from 'react';
import {Router} from 'react-router'; //react-router-dom内部就是靠react-router
import {LOCATION_CHANGE} from './constant'
import {ReactReduxContext} from 'react-redux';

class ConnectedRouter extends Component {
    static contextType = ReactReduxContext;

    componentDidMount() {
        //每当路径发生变化之后(通过调用this.props.history.push、replace、go等方法)，都会执行此监听函数，并传入二个参数，新的路径，新的动作(不是redux里的action，就是一个字符串)
        this.unlistener = this.props.history.listen((location,action)=>{
            this.context.store.dispatch({
                type:LOCATION_CHANGE
                ,payload:{location,action}
            })
        })
    }

    componentWillUnmount() {
        this.unlistener();
    }

    render() {
        let {history, children} = this.props;
        return (
            <Router history={history}>
                {children}
            </Router>
        )
    }
}

export default ConnectedRouter;
